<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="关键字">
                <a-input v-model="queryParam.$search" placeholder />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="评分大于">
                <a-input v-model="queryParam['doubanScore[$gte]']" placeholder />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="出版时间">
                <a-range-picker v-model="queryParamPrev.publicationDateRange" />
              </a-form-item>
            </a-col>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="advanced && { float: 'right', overflow: 'hidden' } || {} "
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  @click="() => this.queryParam = this.queryParamPrev= {}"
                >重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">添加</a-button>
        <a-dropdown v-action:edit>
          <a-menu slot="overlay">
            <a-menu-item key="1">
              <a-icon type="delete" />删除
            </a-menu-item>
            <!-- lock | unlock -->
            <a-menu-item key="2">
              <a-icon type="lock" />锁定
            </a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作
            <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="description" slot-scope="text">
          <ellipsis :length="4" tooltip>{{ text }}</ellipsis>
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDelete(record)">删除</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <step-by-step-modal ref="modal" @ok="handleOk" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { getRoleList, getBooks, postBook, putBook, deleteBook } from '@/api/manage'

import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'
import format from 'date-format'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '名称',
    dataIndex: 'name',
    // scopedSlots: { customRender: 'description' },
  },
  {
    title: '作者',
    dataIndex: 'author',
    // customRender: (text) => text + ' 次',
  },
  {
    title: '出版时间',
    dataIndex: 'publicationDate',
    customRender: (text) => format('yyyy年MM月dd日', new Date(text)),
  },
  {
    title: '标签',
    dataIndex: 'tags',
    customRender: (tags) => tags.join(),
  },
  {
    title: '豆瓣评分',
    dataIndex: 'doubanScore',
    customRender: (score) => (score / 10).toFixed(1),
  },
  {
    title: '页数',
    dataIndex: 'page',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal,
  },
  data() {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      queryParamPrev: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = { ...parameter, ...this.queryParam }
        if (this.queryParamPrev.publicationDateRange) {
          requestParameters['publicationDate[$gte]'] = this.queryParamPrev.publicationDateRange[0].toISOString()
          requestParameters['publicationDate[$lte]'] = this.queryParamPrev.publicationDateRange[1].toISOString()
        }
        console.log('loadData request parameters:', requestParameters)
        return getBooks(requestParameters).then((data) => {
          return { pageNo: 1, totalCount: 10, data }
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  filters: {},
  created() {
    getRoleList({ t: new Date() })
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        length: this.selectedRowKeys.length,
      }
    },
  },
  methods: {
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record, doubanScore: (record.doubanScore / 10).toFixed(1) }
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (typeof values.publicationDate !== 'string') {
            values.publicationDate = values.publicationDate.format('yyyy-MM-DD')
          }
          if (!(values.tags instanceof Array)) {
            values.tags = values.tags.split(',')
          }
          if (values.doubanScore < 10) {
            values.doubanScore = values.doubanScore * 10
          }
          if (values.id > 0) {
            // 修改 e.g.
            putBook(values.id, values).then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('修改成功')
            })
          } else {
            // 新增
            postBook(values).then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.info('新增成功')
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleDelete(record) {
      this.$confirm({
        content: '是否确认删除？',
        onOk: () => {
          deleteBook(record.id).then((res) => {
            this.$refs.table.refresh()
            this.$message.info('删除成功')
          })
        },
      })
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
  },
}
</script>
